<template>
  <div>
    <!-- 分配角色弹窗 -->
    <v-dialog v-model="assignRoleDialog" max-width="400px" persistent>
      <v-card>
        <v-card-title>分配角色</v-card-title>
        <v-card-text>
          <v-select
            v-model="selectedRoles"
            :items="allRoles"
            item-title="name"
            item-value="id"
            label="分配角色"
            multiple
            chips
            clearable
          />
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="closeAssignRoleDialog">关闭</v-btn>
          <v-btn color="primary" @click="onSaveAssignRole">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-dialog v-model="dialog" max-width="600px" persistent>
      <v-card>
        <v-card-title>{{ dialogMode === 'view' ? '查看用户' : dialogMode === 'add' ? '新增用户' : '编辑用户' }}</v-card-title>
        <v-card-text>
          <v-form v-if="dialogMode === 'edit' || dialogMode === 'add'" ref="formRef">
            <v-text-field v-if="dialogMode === 'edit'" v-model="dialogUser.id" label="用户ID" readonly class="mb-2" style="max-width: 320px;" density="compact" />
            <v-text-field v-model="dialogUser.username" label="用户名" :readonly="dialogMode === 'view'" class="mb-2" style="max-width: 320px;" density="compact" />
            <v-text-field v-model="dialogUser.password" label="密码" :readonly="dialogMode === 'view'" class="mb-2" :type="dialogMode === 'view' ? 'text' : 'password'" style="max-width: 320px;" density="compact" />
            <v-text-field v-if="dialogMode === 'edit'" v-model="dialogUser.status" label="用户状态" :readonly="dialogMode === 'view'" class="mb-2" style="max-width: 320px;" density="compact" />
            <v-text-field v-model="dialogUser.email" label="邮箱" :readonly="dialogMode === 'view'" class="mb-2" style="max-width: 320px;" density="compact" />
            <v-text-field v-model="dialogUser.phone" label="手机号" :readonly="dialogMode === 'view'" class="mb-2" style="max-width: 320px;" density="compact" />
          </v-form>
          <div v-else class="user-view-list">
            <v-list lines="one">
              <v-list-item>
                <v-list-item-title>用户ID</v-list-item-title>
                <v-list-item-subtitle>{{ dialogUser.id }}</v-list-item-subtitle>
              </v-list-item>
              <v-list-item>
                <v-list-item-title>用户名</v-list-item-title>
                <v-list-item-subtitle>{{ dialogUser.username }}</v-list-item-subtitle>
              </v-list-item>
              <v-list-item>
                <v-list-item-title>密码</v-list-item-title>
                <v-list-item-subtitle>{{ dialogUser.password }}</v-list-item-subtitle>
              </v-list-item>
              <v-list-item>
                <v-list-item-title>用户状态</v-list-item-title>
                <v-list-item-subtitle>{{ dialogUser.status === 1 ? '启用' : '停用' }}</v-list-item-subtitle>
              </v-list-item>
              <v-list-item>
                <v-list-item-title>邮箱</v-list-item-title>
                <v-list-item-subtitle>{{ dialogUser.email }}</v-list-item-subtitle>
              </v-list-item>
              <v-list-item>
                <v-list-item-title>手机号</v-list-item-title>
                <v-list-item-subtitle>{{ dialogUser.phone }}</v-list-item-subtitle>
              </v-list-item>
            </v-list>
          </div>
        </v-card-text>
        <v-card-actions>
          <v-spacer />
          <v-btn text @click="closeDialog">关闭</v-btn>
          <v-btn v-if="dialogMode === 'edit' || dialogMode === 'add'" color="primary" @click="onSaveUser">保存</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>
    <v-card class="full-width-card">
      <v-card-title>用户管理</v-card-title>
      <v-card-text>
        <v-row class="mb-4" align="center" no-gutters>
          <v-col cols="12" sm="4" md="3">
            <v-text-field
              v-model="searchUserName"
              label="用户名搜索"
              clearable
              density="comfortable"
              variant="outlined"
              hide-details
              @keyup.enter="onSearch"
            />
          </v-col>
          <v-col cols="12" sm="4" md="3">
            <v-select
              v-model="searchStatus"
              :items="statusOptions"
              label="用户状态"
              clearable
              density="comfortable"
              variant="outlined"
              hide-details
            />
          </v-col>
          <v-col cols="12" sm="4" md="5" class="d-flex justify-end align-center gap-btns">
            <v-btn
              variant="outlined"
              color="grey-darken-1"
              elevation="0"
              rounded
              @click="onSearch"
              size="large"
              class="mr-2"
              style="height: 40px; min-width: 90px; background: rgba(128,128,128,0.08);"
            >
              搜索
            </v-btn>
            <v-btn
              variant="outlined"
              color="grey-darken-1"
              elevation="0"
              rounded
              @click="onAddUser"
              size="large"
              style="height: 40px; min-width: 90px; background: rgba(128,128,128,0.08);"
            >
              新增
            </v-btn>
          </v-col>
        </v-row>
        <UserTable :users="users" :page="page" :page-size="pageSize" @action="onUserAction" />
        <div class="d-flex justify-space-between align-center mt-4">
          <span>本页共 {{ users.length }} 条</span>
          <div class="d-flex align-center">
            <span style="margin-right: 12px;">第{{ page }}页 / 共{{ pageCount }}页</span>
            <UserPagination :page="page" :page-size="pageSize" :total="total" @update:page="onPageChange" />
          </div>
        </div>
      </v-card-text>
    </v-card>
  </div>
</template>

<script setup>
import { ref, onMounted, computed, reactive, nextTick } from 'vue'
import UserTable from '@/components/UserTable.vue'
import UserPagination from '@/components/UserPagination.vue'
import { getUserTree, saveOrUpdateUser, getAllRoles, allocateRole, getUserRolesByUserId } from '@/api/user'

const users = ref([])
const total = ref(0)
const page = ref(1)
const pageSize = ref(20)
const searchUserName = ref('')
const searchStatus = ref(null)
const statusOptions = [
  { title: '全部', value: null },
  { title: '启用', value: 1 },
  { title: '停用', value: 0 },
]

const pageCount = computed(() => Math.max(1, Math.ceil(total.value / pageSize.value)))

const dialog = ref(false)
const dialogMode = ref('view') // 'view' or 'edit' or 'add'
const dialogUser = reactive({})
const formRef = ref(null)

const assignRoleDialog = ref(false)
const allRoles = ref([])
const selectedRoles = ref([])
let assignRoleUser = null

function fetchData() {
  const params = {
    pageNum: page.value,
    pageSize: pageSize.value,
    userName: searchUserName.value
  }
  if (searchStatus.value !== null && searchStatus.value !== undefined && searchStatus.value !== '') {
    params.status = searchStatus.value
  }
  getUserTree(params)
    .then(res => {
      users.value = res.data.list || []
      total.value = res.data.total || 0
    })
}

function onPageChange(val) {
  page.value = val
  fetchData()
}

function onSearch() {
  page.value = 1
  fetchData()
}

function onUserAction({ type, user }) {
  if (type === 'assignRole') {
    assignRoleUser = user
    assignRoleDialog.value = true
    getAllRoles().then(res => {
      allRoles.value = (res.data.list || []).map(role => ({ ...role, id: String(role.id) }))
      getUserRolesByUserId(user.id).then(async r => {
        const userRoles = (r.data.data || []).map(role => String(role.id))
        console.log(userRoles)
        await nextTick()
        selectedRoles.value = userRoles
        console.log(selectedRoles.value)
      })
    })
    return
  }
  dialogMode.value = type
  Object.assign(dialogUser, user)
  dialog.value = true
}

function closeDialog() {
  dialog.value = false
  setTimeout(() => {
    Object.keys(dialogUser).forEach(k => delete dialogUser[k])
  }, 300)
}

function onSaveUser() {
  if (dialogMode.value === 'add') {
    const userDTO = {
      username: dialogUser.username,
      userPwd: dialogUser.password,
      email: dialogUser.email,
      phone: dialogUser.phone,
      status: 1
    }
    saveOrUpdateUser(userDTO).then(() => {
      closeDialog()
      fetchData()
    })
    return
  }
  console.log(dialogUser)
  // 只传允许的字段
  const userDTO = {
    userId: dialogUser.id,
    username: dialogUser.username,
    userPwd: dialogUser.password,
    status: dialogUser.status,
    email: dialogUser.email,
    phone: dialogUser.phone,
  }
  // id 不能编辑，createTime 不能编辑
  // 这里假设后端用 userId
  saveOrUpdateUser(userDTO).then(() => {
    closeDialog()
    fetchData()
  })
}

function closeAssignRoleDialog() {
  assignRoleDialog.value = false
  assignRoleUser = null
  selectedRoles.value = []
}

function onSaveAssignRole() {
  if (!assignRoleUser || !selectedRoles.value.length) return
  allocateRole({
    userId: assignRoleUser.id,
    roleIds: selectedRoles.value.join(',')
  }).then(() => {
    closeAssignRoleDialog()
  })
}

function onAddUser() {
  dialogMode.value = 'add'
  Object.assign(dialogUser, { username: '', password: '', email: '', phone: '' })
  dialog.value = true
}

onMounted(fetchData)
</script>

<style scoped>
.full-width-card {
  width: 100% !important;
  margin: 0 !important;
  box-sizing: border-box;
}
.v-card-text {
  padding: 0 !important;
}
:deep(.v-data-table) {
  padding: 0 !important;
}
.v-btn {
  min-width: 80px;
}
.user-view-list {
  max-width: 320px;
  margin: 0 auto;
}
.gap-btns > .v-btn + .v-btn {
  margin-left: 12px;
}
</style>
